<?php

namespace Common\Logic;

/**
 * 系统消息
*/
class MessageLogic
{
    const TABLE = "user_message";// 用户消息表
    const SYSMSG_TABLE = "message";// 系统消息表

    const SYSTEM_MSG = 1;// 管理系统消息
    const EXPRESS_MSG = 2;// 物流消息
    const FRIEND_MSG = 3;// 好友消息
    const ORDER_MSG = 4;// 订单消息
    const SYSTEM_MSG_SIGLE = 5;// 单独的系统消息

    /**
    * 写入管理系统消息，间接发给用户的
    * @param user_id 接收人 默认0给所有人,支持给多人数组
    * @param admin_id 管理员id 系统默认为0
    * @param category 类型 系统消息：0，活动消息：1 默认为0
    * @param title 标题
    * @param content 内容
    * @param ext 数据
    * @param notice 是否发送推送
    */ 
    public static function sendSystemMsg($msg)
    {
    	if (!array_key_exists('content', $msg)) 
    		return ['status'=>0,'msg'=>'消息内容不能为空','result'=> '' ];

    	if (!array_key_exists('admin_id', $msg)) 
    		$msg['admin_id'] = 0;

    	if ( !array_key_exists('user_id', $msg) ) 
    		$msg['user_id'] = 0;

    	if( $msg['user_id'] == 0 )
    		$msg['type'] = 1;
    	else
    		$msg['type'] = 0;

    	if (!array_key_exists('title', $msg)||empty($msg['title'])) 
    		$msg['title'] = substr($msg['content'], 0,16);
 		
 		if( isset($msg['ext']) )
    		$msg['data'] = serialize($msg['ext']);
    	else
    		$msg['data'] = '';

    	if( !isset($msg['category']) ) 
    		$msg['category'] = 0;

    	$msg['send_time'] = time();

    	$add = M( self::SYSMSG_TABLE )->add($msg);

    	if( !$add )
    		return ['status'=>0,'msg'=>'发送失败','result'=> '' ]; 


    	if( !empty($msg['user_id'] = 0 ) )
    	{

    		$msg['message_id'] = $add;

    		$msg['type'] = self::SYSTEM_MSG;

    		self::sendUserMsg($msg);
    	}

    	return ['status'=>1,'msg'=>'发送成功','result'=> $add ];
    }


    /**
    * 写入用户消息，直接发给用户的
    * @param user_id 接收人 支持给多人数组
    * @param message_id 系统类消息表id 默认0,系统消息类必填
    * @param type 类型 
    * @param title 标题
    * @param content 内容
    * @param ext 数据
    * @param notice 是否发送推送
    */ 
    public static function  sendUserMsg($msg = [])
    {
    	if (!array_key_exists('user_id', $msg)||empty($msg['user_id'])) 
    		return ['status'=>0,'msg'=>'接受人错误','result'=> '' ];

    	if (!array_key_exists('type', $msg)) 
    		return ['status'=>0,'msg'=>'消息类型错误','result'=> '' ];

    	$data = [
    		"type" => $msg['type'],
    		"create_time" => time(),
    	];

    	if ( $msg['type'] == self::SYSTEM_MSG && !array_key_exists('message_id', $msg)) 
    	{
    		if (!array_key_exists('message_id', $msg)) 
    			return ['status'=>0,'msg'=>'系统消息错误','result'=> '' ];
    		$message = M(self::SYSMSG_TABLE)->where(["id"=>$msg['message_id']])->find();
    		if( !$message )
    			return ['status'=>0,'msg'=>'系统消息无效','result'=> '' ];

    		if( !array_key_exists('title', $msg) || empty($msg['title']) )
    			$msg['title'] = substr($message['message'], 0,16);

    		if( !array_key_exists('content', $msg) )
    			$msg['content'] = $message['message'];

    		$data['create_time'] = $message['send_time'];

    		$data['message_id'] = $message['message_id'];
    		
    	}else{
    		if (!array_key_exists('title', $msg)) 
    			return ['status'=>0,'msg'=>'消息标题错误','result'=> '' ];

	    	if (!array_key_exists('content', $msg)) 
	    		return ['status'=>0,'msg'=>'消息内容错误','result'=> '' ];
    	}

    	$data['ext'] = '';

    	if( array_key_exists('ext', $msg) )
    		$data['ext'] = serialize($msg);

    	$data['title'] = $msg['title'];
    	$data['content'] = $msg['content'];

    	if( is_numeric($msg['user_id']) )
		{
			#指定用户
			$data['user_id'] = $msg['user_id'];

			$result = M(self::TABLE)->add($data);

		}elseif(is_array($msg['user_id']))
		{
			#多人
			$all_data = [];

			foreach ($msg['user_id'] as $value) 
			{
				if($value>0)
				{
					$data['user_id'] = $value;
					$all_data[] = $data;
				}
			}

			if(empty($all_data))
				return ['status'=>0,'msg'=>'接受人错误','result'=> '' ];
				
			$result = M(self::TABLE)->addAll($all_data);
		}

    	

    	if( $result && isset($msg['notice']) && $msg['notice'] )
    	{
    		self::sendNotice( $msg );
    	}

    	return $result ? ['status'=>1,'msg'=>'发送成功','result'=> $result ] : ['status'=>0,'msg'=>'发送失败','result'=> '' ];
    }


    /**
    * 读取用户的消息
    * @param user_id 接收人
    * @param unread 只读未读消息
    * @param p 页数
    */ 
    public static function  read($user_id,$type = 0 ,$unread = FALSE)
    {
    	if (empty($user_id)) 
    		return ['status'=>0,'msg'=>'参数错误','result'=> '' ];
    	
    	#如果是管理系统消息
    	if( $type == self::SYSTEM_MSG )
    	{
    		#拉取公共消息
    		

    		$my_msg = M(self::TABLE)->order("create_time desc")->where([
    			"type" => self::SYSTEM_MSG
    		])->find();

    		if($my_msg)
    		{
    			$sysMsgs = M(self::SYSMSG_TABLE)->where([
    				"send_time" => ["gt",$my_msg['create_time']],
    				"type" => 1
    			])->select();
    		}else{
    			$me = M("users")->where(["user_id"=>$user_id])->field('user_id,reg_time')->find();

    			$sysMsgs = M(self::SYSMSG_TABLE)->where([
    				"send_time" => ["gt",$me['reg_time']],
    				"type" => 1
    			])->select();
    		}

    		if( $sysMsgs )
    		{
    			$all_data = [];

    			foreach ($sysMsgs as $key => $v ) 
    			{
    				$all_data[] = [
    					"user_id" => $user_id,
    					"type" => self::SYSTEM_MSG,
    					"status" => 0,
    					"title" => substr($v['message'], 0,16),
    					"content" => $v['message'],
    					"create_time" => $v['send_time'],
    					"message_id" => $v['id'],
    					"ext" => $v['data'],
    				];
    			}
    			unset($v);

    			if( !empty($all_data) )
    			{
    				M(self::TABLE)->addAll($all_data);
    			}
    		}	
    	}

    	$where['user_id'] = $user_id;
		$where['status'] = $unread ? 0 : ["lt",2];		
		if( $type ) $where['type'] = $type;

		$page = I('page') > 0 ? I('page') : ( I('p') ? I('p') : 1);

      	$result = [];
      	$result['count'] = M(self::TABLE)->where($where)->count();// 查询满足要求的总记录数
      	// $Page = new \Think\Page($result['count'],$offset);// 实例化分页类 传入总记录数和每页显示的记录数
      	// $result['list'] = M(self::TABLE)->where($where)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->fetchSql(0)->select();
		$result['list'] = M(self::TABLE)
					  ->where($where)
					  ->order('id desc')
					  ->page($page,10)
		  			  ->fetchSql(0)->select();

      	#标记为已读
      	$ids = [];
		// p($result['list']);die;
      	foreach ($result['list']  as $k => &$v) 
      	{
      		$v['create_time_str'] = date('Y年m月d日',$v['create_time']);
			if( 0 == $v['status'] )
      			$ids[] = $v['id'];

      		$v['ext'] = !empty($v['ext']) ? unserialize($v['ext']) : '';
      	}

      	if( !empty($ids) )
      	{
      		M(self::TABLE)->where("id IN (".implode(",", $ids).")" )->save([
      			"status" => 1,
      			"update_time" => time()
      		]);
      	}

      	return ['status'=>1,'msg'=>'ok','result'=> $result ];
    }

    /**
    * 发送推送
    * @param user_id
    * @param title
    * @param content
    * @param ext
    */ 
    public static function sendNotice( $msg )
    {
    	// 如果选用环信，可以设置一个用户为系统账号，给用户发送推送消息
    	$ImLogic = new ImLogic;

    	$target = is_array($msg['user_id']) ? $msg['user_id'] : [$msg['user_id']];

    	// if( $ImLogic->Easemob->sendText("admin","users",$target,$msg['content'],$msg['ext']) )
		// 	return TRUE;

		$target_type = isset($msg['target_type']) ? $msg['target_type'] : "users";
		$action = isset($msg['action']) ? $msg['action'] : "system";
		
		if( $ImLogic->Easemob->sendCmd("admin",$target_type,$target,$action,$msg['ext']) )
    		return TRUE;

    	return FALSE;
    }
}